package com.hotau;

import java.util.ArrayList;
import java.util.List;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.hotau.location.LoadingFragment;
import com.hotau.location.TogetherFragment;
import com.hotau.member.service.MemberService;
import com.hotau.update.service.UpdateService;
import com.hotau.util.HttpUtil;

public class HotauActivity extends NavigationActivity implements
		OnTouchListener, GestureDetector.OnGestureListener {

	public static int heightPixels = 800;
	public static int widthPixels = 480;
	public static double defaultHeightPixels = 800.0;
	public static double galleryImageRate = 1;

	public boolean receivedNotificationOrder = false;

	public static final String HNAPAY_PRIVATE_KEY = "HJKHKHJKH";

	private LinearLayout ll_right;
	private LinearLayout ll_left;
	private ListView menuListView;
	
	public static HotauActivity INSTANCE;

	private GestureDetector mGestureDetector; // 手势检测器

	public static int window_height = heightPixels;
	public static int window_width = widthPixels; // 屏幕的宽度
	
	private static float SNAP_VELOCITY = 200; // x方向上滑动的距离
	private int SPEED = 30; // 滑动的速度
	private int MAX_WIDTH = 0; // 滑动的最大距离
	private int mScrollX;
	private boolean isScrolling = false;
	private boolean isFinish = true;
	private boolean isMenuOpen = false;
	private boolean hasMeasured = false; // 是否Measured.

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		INSTANCE = this;
		
		window_width = getWindowManager().getDefaultDisplay()
					.getWidth();
		window_height = getWindowManager().getDefaultDisplay()
					.getHeight();
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		heightPixels = dm.heightPixels;
		widthPixels = dm.widthPixels;
		galleryImageRate = HotauActivity.heightPixels / HotauActivity.defaultHeightPixels;

		Log.d("mytag", "屏幕heightPixels=" + HotauActivity.heightPixels
				+ " 屏幕widthPixels=" + HotauActivity.widthPixels + " 比率="
				+ galleryImageRate);
		
		getView();
		setLeftLayout();
		setRightLayout();
		initMenu();

		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		mNotificationManager.cancelAll();
		String type = getIntent().getStringExtra("Type");
		Log.d("mytag", "准备启动。。。。。");
		if (type != null && "1".equals(type)) {
			Log.d("mytag", "PUSH收到通知了。。。");
			receivedNotificationOrder = true;
		} else {
			// do nothing...
		}

		this.pushFragment("", new LoadingFragment());
	}

	protected void getView() {// 得到控件的对象实例
		ll_left = (LinearLayout) findViewById(R.id.layout_left);
		ll_right = (LinearLayout) findViewById(R.id.layout_right);
		menuListView = (ListView) findViewById(R.id.list_menu);
	}

	protected void setLeftLayout() {
		RelativeLayout.LayoutParams leftLayoutParams = (RelativeLayout.LayoutParams) ll_left
				.getLayoutParams();
		leftLayoutParams.setMargins(0, 0,  window_width/ 2 - 20, 0);
		ll_left.setLayoutParams(leftLayoutParams);
	}

	protected void initMenu() {
		List<String> data = new ArrayList<String>();
		data.add("请登录");
		data.add("我要注册");
		data.add("购物车");
		data.add("我要买");
		data.add("我要卖");
		data.add("注销");
		LinearLayout.LayoutParams menuLayoutParams = (LinearLayout.LayoutParams) menuListView
				.getLayoutParams();
		menuLayoutParams.width = window_width / 2 + 30;
		menuListView.setLayoutParams(menuLayoutParams);
		
		menuListView.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, data));
	}

	protected void setRightLayout() {// 设置右边布局的滑动
		ll_right.setOnTouchListener(this);
		mGestureDetector = new GestureDetector(this);
		mGestureDetector.setIsLongpressEnabled(false);// 禁用长按监听
		getMaxX();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (HttpUtil.hasInternet(this) && UpdateService.scheuleTask != null) {
			// UpdateService.scheuleTask.run();
		}
	}

	@Override
	public void onNewIntent(Intent newIntent) {
		super.onNewIntent(newIntent);
		Log.d("mytag", "准备启动onNewIntent。。。。。");
		setIntent(newIntent);
		String type = newIntent.getStringExtra("Type");
		if (type != null && "1".equals(type)) {
			Log.d("mytag", "PUSH收到通知了onNewIntent。。。");
			receivedNotificationOrder = true;
			// this.pushFragment("订单查询", new OrderManagementFragment());
			this.pushFragment("", new TogetherFragment());
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		UpdateService.stopMonitor();
		UpdateService.SHOW_NO_UPDATE = false;
		UpdateService.PROCESSING = false;
		MemberService.logout(this);
	}

	public boolean isReceivedNotificationOrder() {
		return receivedNotificationOrder;
	}

	public void setReceivedNotificationOrder(boolean bool) {
		this.receivedNotificationOrder = bool;
	}

	public String getCurrentTitle() {
		return titleStack.peek();
	}

	void getMaxX() {// 得到滑动的最大宽度,即此layout的宽度
		ViewTreeObserver viewTreeObserver = ll_right.getViewTreeObserver();
		viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {
			@Override
			public boolean onPreDraw() {
				if (!hasMeasured) {
					RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ll_right
							.getLayoutParams(); // layout参数
					layoutParams.width = window_width;
					ll_right.setLayoutParams(layoutParams);
					hasMeasured = true;
					MAX_WIDTH = ll_left.getWidth();// 左边layout宽度
				}
				return true;
			}
		});
	}

	@Override
	public boolean onDown(MotionEvent e) {
		mScrollX = 0;
		isScrolling = false;
		return true;// 将之改为true，不然事件不会向下传递.
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {

		int currentX = (int) e2.getX();
		int lastX = (int) e1.getX();
		if (isMenuOpen) {
			if (!isScrolling && currentX - lastX >= 0) {
				return false;
			}
		} else {
			if (!isScrolling && currentX - lastX <= 0) {
				return false;
			}
		}

		boolean suduEnough = false;
		if (velocityX > HotauActivity.SNAP_VELOCITY
				|| velocityX < -HotauActivity.SNAP_VELOCITY) {
			suduEnough = true;
		} else {
			suduEnough = false;
		}

		doCloseScroll(suduEnough);
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		if (isFinish)
			doScrolling(distanceX);
		return true;
	}

	@Override
	public void onShowPress(MotionEvent e) {

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		if (isFinish) {

			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ll_right
					.getLayoutParams();
			// 左移动
			if (layoutParams.leftMargin >= MAX_WIDTH) {
				new AsynMove().execute(-SPEED);
			} else {
				// 右移动
				new AsynMove().execute(SPEED);
			}
		}
		return true;
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent event) {
		return mGestureDetector.onTouchEvent(event);
	}

	public void doScrolling(float distanceX) {
		isScrolling = true;
		mScrollX += distanceX;// distanceX:向左为正，右为负
		RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ll_right
				.getLayoutParams();

		layoutParams.leftMargin -= mScrollX;
		layoutParams.rightMargin += mScrollX;

		if (layoutParams.leftMargin <= 0) {
			isScrolling = false;// 拖过头了不需要再执行AsynMove了
			layoutParams.leftMargin = 0;
			layoutParams.rightMargin = 0;

		} else if (layoutParams.leftMargin >= MAX_WIDTH) {
			// 拖过头了不需要再执行AsynMove了
			isScrolling = false;
			layoutParams.leftMargin = MAX_WIDTH;
		}
		ll_right.setLayoutParams(layoutParams);
		ll_left.invalidate();
	}

	public void doCloseScroll(boolean suduEnough) {
		if (isFinish) {

			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ll_right
					.getLayoutParams();

			int tempSpeed = SPEED;

			if (isMenuOpen) {
				tempSpeed = -tempSpeed;
			}

			if (suduEnough
					|| (!isMenuOpen && (layoutParams.leftMargin > window_width / 2))
					|| (isMenuOpen && (layoutParams.leftMargin < window_width / 2))) {

				new AsynMove().execute(tempSpeed);
			} else {
				new AsynMove().execute(-tempSpeed);
			}

		}
	}

	class AsynMove extends AsyncTask<Integer, Integer, Void> {

		@Override
		protected Void doInBackground(Integer... params) {
			isFinish = false;
			int times = 0;
			if (MAX_WIDTH % Math.abs(params[0]) == 0)// 整除
				times = MAX_WIDTH / Math.abs(params[0]);
			else
				times = MAX_WIDTH / Math.abs(params[0]) + 1;// 有余数

			for (int i = 0; i < times; i++) {
				publishProgress(params[0]);
				try {
					Thread.sleep(Math.abs(params[0]));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			isFinish = true;
			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ll_right
					.getLayoutParams();
			if (layoutParams.leftMargin >= MAX_WIDTH) {
				isMenuOpen = true;
			} else {
				isMenuOpen = false;
			}
			super.onPostExecute(result);
		}

		/**
		 * update UI
		 */
		@Override
		protected void onProgressUpdate(Integer... values) {
			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ll_right
					.getLayoutParams();
			// 右移动
			if (values[0] > 0) {
				layoutParams.leftMargin = Math.min(layoutParams.leftMargin
						+ values[0], MAX_WIDTH);
				layoutParams.rightMargin = Math.max(layoutParams.rightMargin
						- values[0], -MAX_WIDTH);

			} else {
				// 左移动
				layoutParams.leftMargin = Math.max(layoutParams.leftMargin
						+ values[0], 0);
			}
			ll_right.setLayoutParams(layoutParams);
			ll_left.invalidate();
		}
	}

}